import { electronApp, optimizer } from '@electron-toolkit/utils'
import { app, BrowserWindow, ipcMain, shell } from 'electron'
import icon from '../../resources/icon.png?asset'
import { Md5 } from 'ts-md5'
import * as fs from 'fs'
import * as path from 'path'

import * as cron from 'node-cron'
import { Tweet } from './tweet'
import { handleUA } from './ua-handler'

enum XType {
  UA = 'UA'
}

function getTweets(browserWindow: BrowserWindow, type: XType): void {
  const tweetsMap = {}
  browserWindow.webContents.executeJavaScript(`let articles = []; let tweets = [];`)
  let i = 0
  setTimeout(async () => {
    const img = await browserWindow.webContents.capturePage()
    fs.writeFileSync(path.join('screenshot', new Date().toISOString() + '.png'), img.toPNG())
  }, 20000)
  const interval = setInterval(async () => {
    const articles: Tweet[] = await browserWindow.webContents.executeJavaScript(
      `
          document.scrollingElement.scroll({
              top: ${i * 2345},
              behavior: 'smooth'
          });
          articles = document.querySelectorAll('article[data-testid="tweet"]');
          tweets = [];
          for(const item of articles) {
          const updateDate = new Date(item.querySelector('time').getAttribute('datetime'));
           const text = item.querySelector('[data-testid="tweetText"]').innerText;
           const imgs = item.querySelectorAll('[data-testid="tweetPhoto"] img');
            let images = [];
            for(const img of imgs) {
              images.push(img.src);
            }
            tweets.push({text, images, updateDate});
          }
          tweets;
          `
    )
    for (const article of articles) {
      article.hash = Md5.hashStr(article.text!)
      if (!tweetsMap[article.hash]) {
        tweetsMap[article.hash] = article
      }
    }
    if (i++ > 3) {
      clearInterval(interval)
      switch (type) {
        case XType.UA:
          handleUA(Object.values(tweetsMap))
          break
      }
      browserWindow.loadURL('https://baidu.com')
    }
  }, 10000)
}

function createWindow(): BrowserWindow {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 768,
    height: 900,
    show: true,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      // preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  // mainWindow.webContents.openDevTools()

  mainWindow.webContents.userAgent =
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36'

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  mainWindow.webContents.on('did-navigate', (_, url) => {
    const uri = decodeURI(url)
    if (uri.includes('UNION_ARENA_TCG')) {
      getTweets(mainWindow, XType.UA)
    }
  })

  return mainWindow
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(async () => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  const window = createWindow()

  // 每小时检查一次， 第1/31分钟检查UA的推文
  cron.schedule(
    '2 11,18 * * *',
    () => {
      console.log(new Date().toISOString())
      window.loadURL('https://x.com/UNION_ARENA_TCG')
    },
    {
      scheduled: true,
      timezone: 'Asia/Shanghai'
    }
  )

  window.loadURL('https://x.com/UNION_ARENA_TCG')

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
